/* -- INCLUDES -------------------------------------------------------------- */
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <sys/msg.h>

#include "Watcher.h"
#include "Utils.h"

/* -- PUBLIC FUNCTIONS ------------------------------------------------------ */
int Watcher( char * directory, int msgq )
{
	char buffer[ IN_EVENT_BUF_SIZE ];
	int n, notify, watch;
	unsigned int cursor, len;
	struct inotify_event * event;
	msg_p msg;

	notify = inotify_init();
	if( notify == -1 )
		return -1;

	watch = inotify_add_watch( notify, directory, IN_CREATE | IN_MOVED_TO );
	if( watch == -1 )
		return -1;

	while( (n = read( notify, (void *)&buffer, IN_EVENT_BUF_SIZE )) > 0 ) {
		cursor = 0;
		while( (int)cursor < n ) {
			event = (struct inotify_event *)&buffer[cursor];

			if( event->len > 0 ) {
				len = QUEUE_MSG_SIZE + event->len; /* event->len includes the NULL byte */
				msg = calloc(1, len);
				if( msg != NULL ) {
					msg->type = 1;
					strcpy( msg->text, event->name );
					if( msgsnd( msgq, (void *)msg, len, 0) == -1 ) {
						free( msg );
						PERROR("msgsnd");
					}
				} else {
					PERROR("calloc");
				}
			}

			cursor += IN_EVENT_SIZE + event->len;
		}
	}
	
	inotify_rm_watch( notify, watch );
	close( notify );

	return n;
}
